package com.niannian.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MessageRecieveManager;
import com.niannian.util.MyDate;
import com.niannian.util.UmengPage;
import com.niannian.adapter.FamilyNewsAdapter;
import com.niannian.bean.FNCommentBean;
import com.niannian.bean.FamilyNewsBean;
import com.niannian.util.LoadDataUtil;
import com.niannian.view.PullToRefreshListView;
import com.niannian.view.PullToRefreshListView.IXListViewListener;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 我发布的家庭动态
 * 
 * @author shengl
 * 
 */
public class MyFamilyNewsActivity extends BaseActivity {
	public static final int PLAY_VOICE = 1;
	public static final int DELETE_NEWS = 2;
	public static final int LIST_FOOTER_HIDE = 3;// 隐藏底部
	public static final int LIST_NO_DATA = 4;// 没有数据
	public static final int PUSH_COMMENT = 5;// 发布评论
	public static final int DELETE_NEWS_COMMENT = 6;// 删除动态评论
	public static final int DELETE_NEWS_COMMENT_ANIM = 7;// 删除动态评论,动画完成

	// 动态显示列表
	private PullToRefreshListView list_family_news_info;
	private FamilyNewsAdapter familyAdapter;

	// 消息动态提示
	TextView tv_family_news_tip;
	// 消息提示
	TextView tv_news_info;

	private LoadData loadData;// 加载家庭动态
	String playPath = "";// 需要播放的路径
	String playingPath = "";// 当前播放路径

	TextView tv_family_news_no_data;// 没有数据

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_family_news);
		addActToGroup("All", this);
		initView();
		setLister();
		initTopView();
		loadData = new LoadData();
		loadData.setContext(this);
		loadData.loadOnlyDb(false, getParameters());
		loadData.refresh(getParameters());
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right, iv_top_right3;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("我的动态");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);
		iv_top_right.setImageResource(R.drawable.all_comment_news_tip);

		iv_top_right3 = (ImageView) findViewById(R.id.iv_top_right3);
		iv_top_right3.setVisibility(View.VISIBLE);

		iv_top_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myfinish();
			}
		});
		iv_top_right3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putInt("news_type", 2);
				openActivity(NewsActivity.class, bundle);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

			}
		});

	}

	private void initView() {
		list_family_news_info = (PullToRefreshListView) findViewById(R.id.list_family_news_info);
		list_family_news_info.setXListViewListener(xListViewListener);
		list_family_news_info.setPullLoadEnable(false);
		//list_family_news_info.forceShowHeaderRefresh();
		familyAdapter = new FamilyNewsAdapter(this, nHandler);
		list_family_news_info.setAdapter(familyAdapter);
		familyAdapter.setAdapter(familyAdapter);

		// 消息动态提示
		tv_family_news_tip = (TextView) findViewById(R.id.tv_family_news_tip);
		tv_family_news_tip.setVisibility(View.GONE);

		tv_family_news_no_data = (TextView) findViewById(R.id.tv_family_news_no_data);
		tv_family_news_no_data.setVisibility(View.GONE);
		tv_family_news_no_data.setHint("暂无动态.");

		tv_news_info = (TextView) findViewById(R.id.tv_news_info);
		tv_news_info.setVisibility(View.GONE);
	}

	private void updateContent(List<FamilyNewsBean> beans) {
		if (familyAdapter == null) {
			familyAdapter = new FamilyNewsAdapter(this, nHandler);
			list_family_news_info.setAdapter(familyAdapter);
		}
		familyAdapter.getFDatasList().addAll(beans);
		familyAdapter.notifyDataSetChanged();
		if (familyAdapter.getCount() > 0) {
			tv_family_news_no_data.setVisibility(View.GONE);
		} else {
			tv_family_news_no_data.setVisibility(View.VISIBLE);
		}
	}

	private void setLister() {

		tv_family_news_tip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				list_family_news_info.forceShowHeaderRefresh();
				loadData.refresh(getParameters());
				tv_family_news_tip.setVisibility(View.GONE);
				MessageRecieveManager.FAMILY_NEWS_UPDATE_NUM = 0;
				Intent msgIntent = new Intent(MessageRecieveManager.FAMILY_NEWS_UPDATE_ACTION);
				MyFamilyNewsActivity.this.sendBroadcast(msgIntent);
			}
		});
		tv_news_info.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openActivity(NewsActivity.class);
				// openActivity(FamilyNewsDetailActivity.class);

				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

				tv_news_info.setVisibility(View.GONE);
				MessageRecieveManager.NEWS_UPDATE__NUM = 0;
				Intent msgIntent = new Intent(MessageRecieveManager.NEWS_UPDATE_ACTION);
				MyFamilyNewsActivity.this.sendBroadcast(msgIntent);

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case PUSH_COMMENT:
			jiaComment(data);
			break;

		default:
			break;
		}
	}

	private Map<String, Object> getParameters() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lasttime", 0);
		return map;
	}

	Handler nHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PLAY_VOICE:

				break;
			case DELETE_NEWS:
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("fid", msg.arg1);
				// familyAdapter.getFDatasList().remove(msg.arg2);
				// familyAdapter.notifyDataSetChanged();
				new DeleteNews().init(MyFamilyNewsActivity.this, paramMap, true, "正在删除...").execute();
				
				break;
			case LIST_FOOTER_HIDE:
				list_family_news_info.FooterHide();
				break;
			case DELETE_NEWS_COMMENT:

				Map<String, Object> cParamMap = new HashMap<String, Object>();
				cParamMap.put("fid", msg.arg1);
				cParamMap.put("cid", msg.arg2);
				new DeleteNewsComment().init(MyFamilyNewsActivity.this, cParamMap, true, "正在删除...").execute();
				break;
			case DELETE_NEWS_COMMENT_ANIM:
				familyAdapter.notifyDataSetChanged();

				break;
			default:
				break;
			}
		};
	};

	class LoadData extends LoadDataUtil {

		@Override
		protected String runServerTask(Map<String, Object> parameters) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			return nnSyncApi.getMyPosts(lasttime);
		}

		protected void serverTaskFinally(Map<String, Object> params) {
			onLoad();
		}

		@Override
		protected boolean handleServerSuccess(JSONObject json, Map<String, Object> parameters) {
			onLoad();
			try {
				if (json.getInt("code") == ErrorCode.OK) {
					int lasttime = 0;
					if (!Common.empty(parameters.get("lasttime"))) {
						lasttime = (Integer) parameters.get("lasttime");
					}
					databaseapi.updateFamilyNews(userInfoManager.id, json.getJSONArray("data"), lasttime, "my");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected boolean loadMoreDB(Map<String, Object> parameters, boolean refresh) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			List<FamilyNewsBean> fdata = databaseapi.loadFamilyNews(userInfoManager.id, userInfoManager.family, lasttime, "my");
			list_family_news_info.listNotData(true);
			if (fdata != null) {
				// if (fdata == null || fdata.size() == 0) {
				// list_family_news_info.listNotData(false);
				// nHandler.sendEmptyMessageDelayed(LIST_FOOTER_HIDE, 3000);
				// }
				// if (fdata.size() != 10) {
				// list_family_news_info.listNotData(false);
				// nHandler.sendEmptyMessageDelayed(LIST_FOOTER_HIDE, 3000);
				// } else {
				// list_family_news_info.listNotData(true);
				// }
				if (refresh) {
					familyAdapter.getFDatasList().clear();
				}
				updateContent(fdata);
			} else {
				if (refresh) {
					if (familyAdapter.getCount() > 0) {
						tv_family_news_no_data.setVisibility(View.GONE);
					} else {
						tv_family_news_no_data.setVisibility(View.VISIBLE);
					}
				}
			}

			return false;
		}
	}

	private IXListViewListener xListViewListener = new IXListViewListener() {
		@Override
		public void onRefresh() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					loadData.refresh(getParameters());
					tv_family_news_tip.setVisibility(View.GONE);
					MessageRecieveManager.FAMILY_NEWS_UPDATE_NUM = 0;
					Intent msgIntent = new Intent(MessageRecieveManager.FAMILY_NEWS_UPDATE_ACTION);
					MyFamilyNewsActivity.this.sendBroadcast(msgIntent);
				}
			}, 200);
		}

		@Override
		public void onLoadMore() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					Map<String, Object> map = new HashMap<String, Object>();
					FamilyNewsBean last = null;
					try {
						last = (FamilyNewsBean) familyAdapter.getItem((familyAdapter.getCount() - 1));
					} catch (Exception e) {
						last = null;
					}
					if (last != null) {
						map.put("lasttime", last.getCreated_time());
					} else {
						map.put("lasttime", 0);
					}
					loadData.load(map);
				}
			}, 150);
		}
	};

	private void onLoad() {// 显示拉出来时候的一些信息
		list_family_news_info.stopRefresh();
		list_family_news_info.stopLoadMore();
		list_family_news_info.setRefreshTime(MyDate.getDate());
	}

	@Override
	public void onBackPressed() {
		myfinish();
	}

	protected class DeleteNews extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(MyFamilyNewsActivity.this, "删除动态失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				int fid = (Integer) paramMap.get("fid");
				databaseapi.deleteFamilyNews(userInfoManager.id, fid);

				for (int i = 0; i < familyAdapter.getCount(); i++) {
					if (familyAdapter.getFDatasList().get(i).getId() == fid) {
						familyAdapter.getFDatasList().get(i).setIsdelete(1);
						if (familyAdapter.getCount() - 1 > 0) {
							tv_family_news_no_data.setVisibility(View.GONE);
						} else {
							tv_family_news_no_data.setVisibility(View.VISIBLE);
						}
						familyAdapter.notifyDataSetChanged();
						break;
					}
				}

				Common.tip(MyFamilyNewsActivity.this, "删除动态成功");
			} else {
				Common.tip(MyFamilyNewsActivity.this, ErrorCode.GetErrorMsg(retCode));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			String pid = paramMap.get("fid").toString();
			return nnSyncApi.deleteFamilyNews(pid);
		}
	}

	protected class DeleteNewsComment extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(MyFamilyNewsActivity.this, "删除评论失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {

			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {
					int fid = (Integer) paramMap.get("fid");
					int cid = (Integer) paramMap.get("cid");
					databaseapi.deleteFamilyNewsComment(userInfoManager.id, fid, cid);

					for (int i = 0; i < familyAdapter.getCount(); i++) {
						if (familyAdapter.getFDatasList().get(i).getId() == fid) {

							for (int j = 0; j < familyAdapter.getFDatasList().get(i).getCommentBeans().size(); j++) {
								if (cid == familyAdapter.getFDatasList().get(i).getCommentBeans().get(j).getId()) {
									familyAdapter.getFDatasList().get(i).getCommentBeans().get(j).setIsdelete(1);
									familyAdapter.getFDatasList().get(i).getCommentBeans().remove(j);
									break;
								}
							}
							familyAdapter.notifyDataSetChanged();
							break;
						}
					}

					Common.tip(MyFamilyNewsActivity.this, "删除评论成功");
				} else {
					Common.tip(MyFamilyNewsActivity.this, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

		protected String runTask(Map<String, Object> paramMap) {
			String fid = paramMap.get("fid").toString();
			String cid = paramMap.get("cid").toString();
			return nnSyncApi.deleteFamilyNewsComment(fid, cid);
		}
	}

	protected class pushComment extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(MyFamilyNewsActivity.this, "评论失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				int fid = (Integer) paramMap.get("fid");
				int jiaid = (Integer) paramMap.get("id");
				JSONArray jsonArray = new JSONArray();
				JSONObject jsonObject = paramJSONObject.getJSONObject("data");
				int cid = jsonObject.getInt("id");
				jsonArray.put(jsonObject);
				databaseapi.updateFNComment(userInfoManager.id, jsonArray, 12, true);

				FNCommentBean fncomment = databaseapi.loadOneFNComment(userInfoManager.id, fid, cid);
				if (!Common.empty(fncomment)) {

					for (int i = 0; i < familyAdapter.getFDatasList().size(); i++) {
						if (fid == familyAdapter.getFDatasList().get(i).getId()) {

							List<FNCommentBean> commentBeans = familyAdapter.getFDatasList().get(i).getCommentBeans();
							if (!Common.empty(commentBeans)) {
								for (int j = 0; j < commentBeans.size(); j++) {
									if (jiaid == commentBeans.get(j).getId()) {
										familyAdapter.getFDatasList().get(i).getCommentBeans().remove(j);
										break;
									}
								}
							}
							familyAdapter.getFDatasList().get(i).getCommentBeans().add(fncomment);
							familyAdapter.notifyDataSetChanged();
							break;
						}
					}
				}
			} else {
				Common.tip(MyFamilyNewsActivity.this, ErrorCode.GetErrorMsg(retCode));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			int fid = (Integer) paramMap.get("fid");
			String info = paramMap.get("info").toString();
			String aud = paramMap.get("aud").toString();
			int aud_len = (Integer) paramMap.get("aud_len");
			int reply_to = (Integer) paramMap.get("reply_to");
			return nnSyncApi.FNComment(fid, info, aud, aud_len, reply_to);
		}
	}

	private void jiaComment(Intent data) {
		int jiaid = (int) ((new Date()).getTime() / 1000);
		int fid = data.getExtras().getInt("fid", 0);
		String info = data.getExtras().getString("info", "");
		String aud = data.getExtras().getString("aud", "");
		int aud_len = data.getExtras().getInt("aud_len", 0);
		int reply_to = data.getExtras().getInt("reply_to", 0);
		String reply_to_nickname = data.getExtras().getString("reply_to_nickname", "");

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", jiaid);
		paramMap.put("fid", fid);
		paramMap.put("info", info);
		paramMap.put("aud", aud);
		paramMap.put("aud_len", aud_len);
		paramMap.put("reply_to", reply_to);

		FNCommentBean fncomment = new FNCommentBean();
		fncomment.setAud(aud);
		fncomment.setAud_len(aud_len);
		fncomment.setAuthor(userInfoManager.id);
		fncomment.setAuthor_avatar(userInfoManager.avatar);
		fncomment.setAuthor_nickname(userInfoManager.nickname);
		fncomment.setCreated_time(jiaid);
		fncomment.setId(jiaid);
		fncomment.setInfo(info);
		fncomment.setPost(fid);
		fncomment.setReply_to(reply_to);
		fncomment.setReply_to_nickname(reply_to_nickname);
		addComment(fid, fncomment);
		new pushComment().init(paramMap).execute();
	}

	private void addComment(int fid, FNCommentBean fncomment) {
		if (!Common.empty(fncomment)) {

			for (int i = 0; i < familyAdapter.getFDatasList().size(); i++) {
				if (fid == familyAdapter.getFDatasList().get(i).getId()) {
					if (Common.empty(familyAdapter.getFDatasList().get(i).getCommentBeans())) {
						familyAdapter.getFDatasList().get(i).setCommentBeans(new ArrayList<FNCommentBean>());
					}
					familyAdapter.getFDatasList().get(i).getCommentBeans().add(fncomment);
					familyAdapter.notifyDataSetChanged();
					break;
				}
			}

		}
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPage.mypost_face);
		MobclickAgent.onResume(this);

	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPage.mypost_face);
		MobclickAgent.onPause(this);
	}
}
